package cn.wolfcode.web.controller;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProduct;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.ISeckillProductService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/seckillProduct")
@Slf4j
public class SeckillProductController {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //注意redis中的vo初始化
    @RequestMapping("/queryByTime1")
    public Result<List<SeckillProductVo>> getSeckKillVo(Long time){
        //根据秒杀商品的time场次，最终要封装返回SeckillProductVo
        List<SeckillProductVo> seckillProductVOs = seckillProductService.querySeckProductVOs(time);
        return Result.success(seckillProductVOs);
    }
    //根据time,从redis中查询VO集合
    @RequestMapping("/queryByTime")
    public Result<List<SeckillProductVo>> getSeckKill(Long time){
        //根据秒杀商品的time场次，最终要封装返回SeckillProductVo
        List<SeckillProductVo> seckillProductVOs = seckillProductService.querySeckProductVOsFromRedis(time);
        return Result.success(seckillProductVOs);
    }
    //秒杀商品vo详情，seckillProduct/find?time=10&seckillId=2
    @RequestMapping("/find")
    public Result<SeckillProductVo> getSeckillProducrVO(Long time,Long seckillId){
        //先从缓存中查，如果没有再去数据库查
        //先从缓存中查
        SeckillProductVo seckillProductVo=null;
        Object stringVo = stringRedisTemplate.opsForHash()
                .get(SeckillRedisKey.SECKILL_PRODUCT_LIST.getRealKey(String.valueOf(time)), seckillId.toString());
        if(stringVo!=null){
            seckillProductVo = JSON.parseObject(stringVo.toString(), SeckillProductVo.class);
        }else {
            //从数据库查询(升级了)
            seckillProductVo=seckillProductService.getSeckillProductVO(time,seckillId);
        }
        return Result.success(seckillProductVo);
    }

    //查询所有秒杀商品 //querySeckillProducts
    @RequestMapping("querySeckillProducts")
    public Result<List<SeckillProduct>> getSeckKillProducts(){
        List<SeckillProduct> seckillProducts = seckillProductService.querySeckProducts();
        return Result.success(seckillProducts);
    }

}
